package com.rongshu.view.userInfo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.home.listener.OnItemClickListener;
import com.rongshu.view.userInfo.adapter.PaySetMealAdapter;
import com.rongshu.view.userInfo.decoration.SpacesItemDecoration;
import com.rongshu.view.userInfo.dialog.PayDialog;
import com.rongshu.view.userInfo.entity.OrderInfo;
import com.rongshu.view.userInfo.entity.PayResult;
import com.rongshu.view.userInfo.entity.PaySetMeal;
import com.rongshu.view.userInfo.iview.PayView;
import com.rongshu.view.userInfo.listener.OnPayClickListener;
import com.rongshu.view.userInfo.presenter.PayPresenter;
import com.utils.permissions.OnPermission;
import com.utils.permissions.XXPermissions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PayActivity extends BaseActivity<PayPresenter> implements PayView, OnItemClickListener {
    @BindView(R.id.top_layout)
    RelativeLayout top_layout;
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;//标题
    @BindView(R.id.txt_top_function)
    TextView txt_top_function;
    @BindView(R.id.txt_tree_leaves_balance)
    TextView txt_tree_leaves_balance;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    //layoutmanager
    private GridLayoutManager manager = null;
    //adapter
    private PaySetMealAdapter adapter = null;
    //intent
    private Intent intent = null;
    //map
    private Map<String, Object> map = null;
    //dialog
    private PayDialog mPayDialog = null;
    //permission
    private String[] mPermissionList = new String[]{Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //what
    private static final int SDK_PAY_FLAG = 1;
    //handler
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        showSuccessMsg(getString(R.string.pay_success) + payResult);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        toast(getString(R.string.pay_failed) + payResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_pay_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new PayPresenter(this), this);
        //设置top背景色
        top_layout.setBackgroundColor(ContextCompat.getColor(this, R.color.color_f7f7f7));
        //设置title
        txt_top_title.setText(R.string.pay);
        txt_top_function.setVisibility(View.VISIBLE);
        txt_top_function.setTextColor(getResources().getColor(R.color.color_2c2c2c));
        txt_top_function.setText("使用明细");
        //manager
        manager = new GridLayoutManager(this, 3);
        //adapter
        adapter = new PaySetMealAdapter(this);
        adapter.setOnItemClickListener(this);
        //recycler
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new SpacesItemDecoration(this));
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void updateViews(boolean isRefresh) {
        getRongShuLeaf();
    }

    /**
     * 获取榕树叶充值套餐列表
     */
    private void getRongShuLeaf() {
        map = new HashMap<>();
        map.put("rnd", 0);
        presenter.getRongShuLeaf(0, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 点击充值生成订单
     */
    private void getTopUp(int pay_device, int pay_way, int money, int LeafNumber) {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("pay_device", pay_device);//设备(1.安卓 2.ios)
        map.put("pay_way", pay_way);//充值类型(1.微信 2.支付宝 3.苹果支付 4.馈赠)
        map.put("money", money);
        map.put("LeafNumber", LeafNumber);
        presenter.getTopUp((int) map.get("user_id"),
                (int) map.get("pay_device"),
                (int) map.get("pay_way"),
                (int) map.get("money"),
                (int) map.get("LeafNumber"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 支付dialog
     */
    private void showPayDialog(final double money, final int banyan_tree_leaves) {
        PayDialog.Builder builder = new PayDialog.Builder(this);
        mPayDialog = builder
                .setMoney(money)
                .setBanyan_tree_leaves(banyan_tree_leaves)
                .setOnPayClickListener(new OnPayClickListener() {
                    @Override
                    public void onPayClick(PayDialog dialog) {
                        dialog.dismiss();
                        requestPermission(money, banyan_tree_leaves);
                    }
                })
                .create();
        mPayDialog.show();
    }

    /**
     * 成功提示
     */
    public void showSuccessMsg(String content) {
        toast(content);
    }

    @OnClick({R.id.layout_back, R.id.txt_top_function, R.id.txt_event_equity})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
            case R.id.txt_top_function://使用明细
                intent = new Intent(this, PayDetailActivity.class);
                startActivity(intent);
                break;
            case R.id.txt_event_equity://活动权益
                intent = new Intent(this, EventEquitiesActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private void requestPermission(final double money, final int banyan_tree_leaves) {
        XXPermissions.with(this).permission(mPermissionList).request(new OnPermission() {
            @Override
            public void hasPermission(List<String> granted, boolean isAll) {
                getTopUp(1, 2, (int) money, banyan_tree_leaves);
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {

            }
        });
    }

    /**
     * 获取榕树叶充值套餐列表
     *
     * @param paySetMeal
     */
    @Override
    public void onRongShuLeaf(PaySetMeal paySetMeal) {
        if (paySetMeal.getErrCode() == 0) {
            List<PaySetMeal.ResponseBean> responseBeanList = paySetMeal.getResponse();
            if (responseBeanList != null) {
                adapter.setPaySetMeals(responseBeanList);
                adapter.notifyDataSetChanged();
            }
        } else {
            toast(paySetMeal.getErrMsg());
        }
    }

    @Override
    public void onOrderInfo(OrderInfo info) {
        pay(info.getResponse());
    }


    /**
     * 支付业务
     */
    private void pay(final String orderInfo) {
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * item click
     *
     * @param position
     */
    @Override
    public void onItemClick(int position) {
        if (adapter != null) {
            List<PaySetMeal.ResponseBean> responseBeanList = adapter.getPaySetMeals();
            for (int i = 0; i < responseBeanList.size(); i++) {
                responseBeanList.get(i).setIs_select(i == position ? true : false);
            }
            adapter.notifyDataSetChanged();
            //调用支付dialog
            PaySetMeal.ResponseBean responseBean = adapter.getPaySetMeals().get(position);
            if (responseBean != null) {
                showPayDialog(responseBean.getRmb(), responseBean.getRongshu_leaf_num());
            }
        }
    }
}
